import { defineComponent, computed, ref, onMounted, watch } from 'vue';
import Viewer from '@wf/components/bpmnjs/components/Viewer';
import { getBpmnjs } from '@wf/api/wf/definition';
import { getProcessNode } from '@wf/api/wf/instance';
import { Base64 } from 'js-base64';

export default defineComponent({
  props: {
    id: {
      type: String,
      default: undefined
    },
    wfCode: {
      type: String,
      default: undefined
    },
    taskId: {
      type: String,
      default: undefined
    },
    processInstanceId: {
      type: String,
      default: ''
    },
    deploymentId: {
      type: String,
      default: undefined
    }
  },
  setup(props, { emit }) {
    const processXml = ref<string | undefined>(undefined);
    const processConfig = ref<Record<string, string>>({});
    const processNodes = ref<Record<string, any>>({});
    const subProcessXml = ref<string | undefined>(undefined);

    onMounted(() => {
      getFlowXml();
      // getProcessNodes();
    });

    const getFlowXml = () => {
      const params = {
        modelId: props.id,
        wfCode: props.wfCode,
        deploymentId: props.deploymentId
      };
      getBpmnjs(params).then((res: any) => {
        const { model, wfCode, name, subProcessList } = res;
        processXml.value = Base64.decode(model);
        if (subProcessList) {
          subProcessXml.value = Base64.decode(subProcessList);
        }
        processConfig.value = {
          processId: wfCode,
          processName: name
        };
      });
    };

    const getProcessNodes = () => {
      if (props.processInstanceId) {
        const taskId = props.taskId || '';
        getProcessNode(props.processInstanceId, taskId).then((res: any) => {
          processNodes.value = res.data;
        });
      }
    };

    watch(
      () => props.processInstanceId,
      () => {
        getProcessNodes();
      },
      { immediate: true }
    );

    /* 组件渲染 */
    return () => <Viewer v-model={[processXml.value, 'xml']} config={processConfig.value} processNodes={processNodes.value} subProcessXml={subProcessXml.value} />;
  }
});
